<template>
  <el-dialog v-model="dialog.visible" :title="title" width="50%" @close="handleCloseDialog">
    <el-card shadow="always" class="table-card">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input v-model="queryParams.keywords" placeholder="请输入关键字" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <BasePageTable
        ref="basePageTableRef"
        :table-data="tableData"
        :table-columns-data="tableColumnsData"
        :total="total"
        :loading="loading"
        @current-change="handleCurrentChange"
      >
        <template #gender="{ row, name }">
          {{ getLabelByValue(GenderEnum, row.gender) }}
        </template>
        <template #status="{ row, name }">
          <el-tag :type="UserStatusEnum.ENABLED.value === row.status ? 'success' : 'info'">
            {{ getLabelByValue(UserStatusEnum, row.status) }}
          </el-tag>
        </template>
        <template #avatar="{ row, name }">
          <el-avatar :size="40" :src="row.avatar" />
        </template>
      </BasePageTable>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getAccessToken } from "@/utils/auth";
import { GenderEnum, UserStatusEnum, UserTypeEnum } from "@/enums/system/UserEnum";
import EnumSelect from "@/components/EnumSelect/index.vue";
import { ElMessage, UploadProps } from "element-plus";
import UserAPI, { UserForm } from "@/api/system/user";
import PartnerUser from "@/api/system/partner-user";
import { getLabelByValue } from "@/utils/enums";
import BasePageTable from "@/components/BasePageTable/index.vue";
// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData"]);
// 弹窗
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  defaultRowId: {
    type: String,
    default: "",
  },
  data: {},
});

const dialog = reactive({
  title: "",
  visible: false,
});
const basePageTableRef = ref();
const loading = ref(false);
const total = ref(0);
const queryFormRef = ref();
const multipleSelection = ref([]);
const currentRow = ref([]);
const queryParams = reactive({
  keywords: "",
  pageNum: 1,
  pageSize: 10,
});
const tableData = ref([]);
const tableColumnsData = ref([
  {
    type: "selection",
  },
  {
    prop: "avatar",
    label: "头像",
    width: 100,
    showOverflowTooltip: true,
    customSlot: "avatar",
  },
  {
    prop: "username",
    label: "用户名",
    showOverflowTooltip: true,
  },
  {
    prop: "nickname",
    label: "用户昵称",
    showOverflowTooltip: true,
  },
  {
    prop: "mobile",
    label: "手机号",
    width: 200,
    showOverflowTooltip: true,
  },
  {
    prop: "gender",
    label: "性别",
    width: 100,
    showOverflowTooltip: true,
    customSlot: "gender", // 自定义插槽名称
  },
  {
    prop: "status",
    label: "用户状态",
    width: 200,
    showOverflowTooltip: true,
    customSlot: "status",
  },
  {
    prop: "roleNames",
    label: "角色名称",
    width: 200,
    showOverflowTooltip: true,
  },
]);

const formData = ref<UserForm>({
  id: 0,
  nickname: "",
  userType: UserTypeEnum.PRACTITIONER.value,
  mobile: "",
  password: "",
  gender: 0,
  avatar: "",
  email: "",
  status: 0,
  companyId: 0,
  roleIds: [],
  openId: "",
});
const formRules = reactive({
  mobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度为6位", trigger: "blur" },
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
});

const title = computed(() => {
  return formData.value.id ? "编辑" : "新增";
});

// 监听外部传入的 modelValue，更新内部 visible 状态
watch(
  () => props.modelValue,
  (newValue) => {
    dialog.visible = newValue;
    if (newValue) {
      handleQuery();
    }
  }
);

function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
    .then((data) => {
      tableData.value = data.list || [];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

async function handleSubmit() {
  try {
    if (!currentRow.value) return ElMessage.error("请选择关联用户");
    const params = {
      merchantUserId: currentRow.value.id,
    };
    await PartnerUser.add(params);
    ElMessage.success("成功");
    emit("loadData");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  emit("update:modelValue", false); // 关闭弹窗
}

const handleCurrentChange = (val) => {
  currentRow.value = val;
};
</script>
<style style="scss" scoped>
.table-card {
  margin-bottom: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
